import 'dart:async';

import 'package:dot_navigation_bar/dot_navigation_bar.dart';
import 'package:efood_multivendor/controller/cart_controller.dart';
import 'package:efood_multivendor/controller/location_controller.dart';
import 'package:efood_multivendor/controller/order_controller.dart';
import 'package:efood_multivendor/controller/product_controller.dart';
import 'package:efood_multivendor/controller/splash_controller.dart';
import 'package:efood_multivendor/data/model/body/review_body.dart';
import 'package:efood_multivendor/data/model/response/order_details_model.dart';
import 'package:efood_multivendor/data/repository/location_repo.dart';
import 'package:efood_multivendor/helper/responsive_helper.dart';
import 'package:efood_multivendor/helper/route_helper.dart';
import 'package:efood_multivendor/helper/size_config.dart';
import 'package:efood_multivendor/util/app_constants.dart';
import 'package:efood_multivendor/util/dimensions.dart';
import 'package:efood_multivendor/util/styles.dart';
import 'package:efood_multivendor/view/screens/home/home_screen.dart';
import 'package:efood_multivendor/view/screens/order/order_screen.dart';
import 'package:efood_multivendor/view/screens/profile/profile_screen.dart';
import 'package:efood_multivendor/view/screens/review/rate_review_screen.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:geolocator/geolocator.dart';
import 'package:get/get.dart';

class DashboardScreen extends StatefulWidget {
  final int pageIndex;
  final String page;
  DashboardScreen({required this.pageIndex, this.page = ''});

  @override
  _DashboardScreenState createState() => _DashboardScreenState();
}

class _DashboardScreenState extends State<DashboardScreen> {
  late PageController _pageController;
  int _pageIndex = 0;
  late List<Widget> _screens;
  GlobalKey<ScaffoldMessengerState> _scaffoldKey = GlobalKey();
  bool _canExit = GetPlatform.isWeb ? true : false;
  bool reload = false;
  LocationRepo? locationRepo;
  Future<LocationPermission> _geoPermissions = Geolocator.checkPermission();
  @override
  void initState() {
    super.initState();

    _pageIndex = widget.pageIndex;

    _pageController = PageController(initialPage: widget.pageIndex);

    _screens = [
      HomeScreen(),
      OrderScreen(),
      ProfileScreen(),
    ];

    WidgetsBinding.instance.addPostFrameCallback((_) async {
      if (widget.page.isNotEmpty &&
          (widget.page == "SplashScreen" || widget.page.isEmpty)) {
        await Get.find<LocationController>().getCurrentLocation(false);
      }

      if (Get.find<SplashController>().isFirstOpen) {
        Get.find<SplashController>().loadData(true);
      }

      if (Get.find<SplashController>().isFirstOpen &&
          Get.find<ProductController>().unreviewedOrdersResponse != null &&
          Get.find<ProductController>().unreviewedOrdersResponse?.totalSize !=
              null &&
          Get.find<ProductController>().unreviewedOrdersResponse!.totalSize! >
              0) {
        showAlertDialog(
            Get.find<OrderController>().orderDetails!,
            Get.find<ProductController>()
                .unreviewedOrdersResponse!
                .reviewOrders![0]
                .id!);
      }
    });
  }

  // void didChangeAppLifecycleState(AppLifecycleState state) {
  //   switch (state) {
  //     case AppLifecycleState.resumed:
  //       // setState(() {
  //       //   _geoPermissions = Geolocator.checkPermission();
  //       // });
  //       break;
  //     case AppLifecycleState.inactive:
  //       break;
  //     case AppLifecycleState.paused:
  //       break;
  //     case AppLifecycleState.detached:
  //       break;
  //   }
  // }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () async {
          if (_pageIndex != 0) {
            _setPage(0);
            return false;
          } else {
            if (_canExit) {
              return true;
            } else {
              ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                content: Text('back_press_again_to_exit'.tr,
                    style: TextStyle(color: Colors.white)),
                behavior: SnackBarBehavior.floating,
                backgroundColor: Colors.green,
                duration: Duration(seconds: 2),
                margin: EdgeInsets.all(Dimensions.PADDING_SIZE_SMALL),
              ));
              _canExit = true;
              Timer(Duration(seconds: 2), () {
                _canExit = false;
              });
              return false;
            }
          }
        },
        child: FutureBuilder<LocationPermission>(
            future: _geoPermissions,
            initialData: null,
            builder: (BuildContext context,
                AsyncSnapshot<LocationPermission> permissions) {
              return Stack(
                children: [
                  Scaffold(
                      key: _scaffoldKey,
                      extendBody: true,
                      body: _screens[_pageIndex],
                      bottomNavigationBar: ResponsiveHelper.isDesktop(context)
                          ? SizedBox()
                          : ClipRect(
                              child: Container(
                              width: 100.w,
                              decoration: BoxDecoration(color: Colors.white),
                              child: DotNavigationBar(
                                enablePaddingAnimation: false,
                                margin: EdgeInsets.only(left: 0, right: 0),
                                dotIndicatorColor: Colors.transparent,
                                backgroundColor: Colors.white,
                                marginR: EdgeInsets.only(
                                    left: 25, right: 25, bottom: 0),
                                paddingR: EdgeInsets.only(
                                    bottom: 5, top: 5, right: 10),
                                currentIndex: _pageIndex,
                                unselectedItemColor: Colors.grey[300],
                                onTap: _setPage,
                                items: <DotNavigationBarItem>[
                                  DotNavigationBarItem(
                                    icon: SvgPicture.asset(
                                      'assets/icons/home.svg',
                                      color: _pageIndex == 0
                                          ? Theme.of(context)
                                              .colorScheme
                                              .secondary
                                          : Color.fromARGB(170, 0, 0, 0),
                                      height: 26,
                                    ),
                                  ),
                                  DotNavigationBarItem(
                                    icon: SvgPicture.asset(
                                      'assets/icons/order.svg',
                                      color: _pageIndex == 1
                                          ? Theme.of(context)
                                              .colorScheme
                                              .secondary
                                          : Color.fromARGB(170, 0, 0, 0),
                                      height: 26,
                                    ),
                                  ),
                                  DotNavigationBarItem(
                                    icon: SvgPicture.asset(
                                      'assets/icons/pro.svg',
                                      color: _pageIndex == 2
                                          ? Theme.of(context)
                                              .colorScheme
                                              .secondary
                                          : Color.fromARGB(170, 0, 0, 0),
                                      height: 26,
                                    ),
                                  ),
                                ],
                              ),
                            ))),
                  AppConstants.BASE_URL.contains('alpha')
                      ? Align(
                          alignment: Alignment.topRight,
                          child: Container(
                            padding: EdgeInsets.only(top: 50, right: 50),
                            child: Banner(
                              color: Colors.red,
                              message: "Alpha",
                              location: BannerLocation.bottomStart,
                            ),
                          ),
                        )
                      : SizedBox()
                ],
              );
            }));
  }

  void _setPage(int pageIndex) {
    setState(() {
      _pageIndex = pageIndex;
    });
  }

  void showAlertDialog(OrderDetails orderDetails, int orderId) {
    AlertDialog alert3 = AlertDialog(
      backgroundColor: Theme.of(context).cardColor,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(Dimensions.RADIUS_EXTRA_LARGE),
      ),
      title: Center(
          child: Text('review'.tr,
              style: sfRegular.copyWith(
                  fontSize: Dimensions.fontSizeLarge,
                  fontWeight: FontWeight.bold))),
      actions: [
        Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
          Padding(
            padding: EdgeInsets.only(left: 8.w),
            child: TextButton(
                onPressed: () {
                  Get.find<SplashController>().setFirstOpen();
                  Get.back();
                  DelvieryManCancelPopupBody cancelBody =
                      DelvieryManCancelPopupBody(
                          orderId: orderId.toString(), status: 0);
                  Get.find<ProductController>()
                      .cancelDeliveryManReviewPopup(cancelBody);
                },
                child: Text('cancel'.tr,
                    style: TextStyle(
                        color: Colors.grey[500],
                        fontSize: Dimensions.fontSizeLarge,
                        fontWeight: FontWeight.bold))),
          ),
          Padding(
              padding: EdgeInsets.only(right: 8.w),
              child: TextButton(
                  onPressed: () {
                    Get.find<SplashController>().setFirstOpen();
                    Get.until((route) => Get.isDialogOpen != true);
                    List<Details> _orderDetailsList = [];
                    Get.find<OrderController>()
                        .orderDetails
                        ?.details
                        ?.forEach((orderDetail) {
                      _orderDetailsList.add(orderDetail);
                    });
                    Get.toNamed(RouteHelper.getReviewRoute(),
                        arguments: RateReviewScreen(
                          orderDetailsList: _orderDetailsList,
                          deliveryMan: orderDetails.deliveryMan,
                          isFoodReviewed: false,
                          isFromHome: true,
                          orderId: orderId.toString(),
                        ));
                  },
                  child: Text('review'.tr,
                      style: TextStyle(
                          fontSize: Dimensions.fontSizeLarge,
                          fontWeight: FontWeight.bold))))
        ])
      ],
      content: Container(
          width: 60.w,
          height: 7.h,
          padding: EdgeInsets.zero,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius:
                BorderRadius.circular(Dimensions.PADDING_SIZE_EXTRA_LARGE),
          ),
          child: Center(
            child: !Get.find<CartController>().isLoading
                ? Text('review_driver'.tr,
                    style:
                        sfRegular.copyWith(fontSize: Dimensions.fontSizeLarge),
                    textAlign: TextAlign.center,
                    softWrap: true,
                    maxLines: 4)
                : CircularProgressIndicator.adaptive(
                    valueColor: AlwaysStoppedAnimation<Color>(
                        Theme.of(context).colorScheme.secondary),
                    backgroundColor: Theme.of(context).colorScheme.primary,
                  ),
          )),
    );
    Get.dialog(alert3, barrierDismissible: true);
  }
}
